<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/3
 * Time: 16:12
 */
namespace app\admin\controller;

use app\common\Common;
use think\Controller;
use think\Request;

class Base extends Controller
{
    /**
     * 正确状态码
     * @var int
     */
    protected $t_code;

    /**
     * 错误状态码
     * @var int
     */
    protected $f_code;


    public function _initialize($str=null)
    {
        header("Access-Control-Allow-Origin: *");
        $this->t_code=config('t_code');
        $this->f_code=config('f_code');
    }
    public function txFunc($openid,$money,$desc)
    {
        $this->payment($openid,$money);

        $partner_trade_no = md5($openid.time().'qwertyuiopasdfghjklzxcvbnm'.rand(0,99));
        $data = array(
            'mch_appid' =>'wx640ebd4c31a05f10',//协会appid
            'mchid' => '1510775671',//微信支付商户号
            'nonce_str' => $this->getNonceStr(), //随机字符串
            'partner_trade_no' => $partner_trade_no , //商户订单号，需要唯一
            'openid' => $openid,
            'check_name' => 'NO_CHECK', //OPTION_CHECK不强制校验真实姓名, FORCE_CHECK：强制 NO_CHECK：
            'amount' => $money, //付款金额单位为分
            'desc' => $desc,
            'spbill_create_ip' => $this->request->ip(),
        );
        //生成签名
        $data['sign']=$this->makeSign($data);

        //构造XML数据（数据包要以xml格式进行发送）
        $xmldata = $this->arrToXml($data);

        //请求url
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
        //发送post请求
        $res = $this->curl_post_ssl($url,$xmldata);
        return $res;
    }
    function payment($openid,$money){

        $user = Common::db_count('id,user_name','','drh_user_info',"user_open_id='{$openid}'")[0]??array();
        Common::db_insert('drh_payment_water',[
            'open_id'=>$openid,
            'user_time'=>time(),
            'user_name'=>$user['user_name'],
            'user_money'=>$money,
            'user_id'=>$user['id']
        ]);
    }
    function curl_post_ssl($url, $xmldata, $second = 30, $aHeader = array()){
        $isdir = $_SERVER['DOCUMENT_ROOT']."/";//证书位置;绝对路径

        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置执行最长秒数
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');//证书类型
        curl_setopt($ch, CURLOPT_SSLCERT, $isdir . 'apiclient_cert.pem');//证书位置
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');//CURLOPT_SSLKEY中规定的私钥的加密类型
        curl_setopt($ch, CURLOPT_SSLKEY, $isdir . 'apiclient_key.pem');//证书位置
        curl_setopt($ch, CURLOPT_CAINFO, 'PEM');
        curl_setopt($ch, CURLOPT_CAINFO, $isdir . 'rootca.pem');
        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);//设置头部
        }
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);//全部数据使用HTTP协议中的"POST"操作来发送
        $data = curl_exec($ch);//执行回话
        if ($data) {
            curl_close($ch);
            return $this->xmlToArray($data);
        } else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }
    function getNonceStr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 签名
     * @param $data
     * @return string
     */
    function makeSign($data)
    {
        $key="drh12345678912345678912345678912";
        // 关联排序
        ksort($data);
        // 字典排序
        $str = http_build_query($data);
        // 添加商户密钥
        $str .= '&key=' . $key;
        // 清理空格
        $str = urldecode($str);
        $str = md5($str);
        // 转换大写
        $result = strtoupper($str);
        return $result;
    }

    /**
     * 数组转XML
     * @param $data
     * @return string
     */
    function arrToXml($data)
    {
        $xml = "<xml>";
        //  遍历组合
        foreach ($data as $k=>$v){
            $xml.='<'.$k.'>'.$v.'</'.$k.'>';
        }
        $xml .= '</xml>';
        return $xml;
    }

    /**
     * XML转数组
     * @param string
     * return $data
     * */
    function xmlToArray($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }

}
